package com.wisenet.controller.client.security;

import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.wisenet.annotation.LoginValidate;
import com.wisenet.cache.SimpleCacheProvider;
import com.wisenet.common.WxConst;
import com.wisenet.controller.PlatformController;
import com.wisenet.entity.WeixinPubno;
import com.wisenet.service.wxpubno.WeixinService;
import com.wisenet.wx.util.WeChatApiUtil;
import com.wisenet.wx.util.WeixinUtil;

/**
 * 内容安全检查控制类
 * @author fzh
 */
@RestController
@RequestMapping("/security")
public class SecurityCheckController extends PlatformController {
	// 日志
	private static final Logger logger = Logger.getLogger(SecurityCheckController.class);
	@Autowired
	private WeixinService weixinService;
	@Autowired
	private SimpleCacheProvider simpleCacheProvider;
	
	/**
	 * 内容检测
	 * @param content 文本内容，长度不超过 500KB
	 * @param appid
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/checkmsg", method = RequestMethod.POST)
	public JSONObject checkContent(String content, String appid) {
		JSONObject jsonObject = getJsonResult(content, appid);
		if (jsonObject.getBoolean(SUCCESS)) {
			// 获取小程序信息
			WeixinPubno pubno = simpleCacheProvider.get(appid);
			if (pubno == null) {
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, "APP不存在");
				return jsonObject;
			}
			// 获取TOKEN
			String token = weixinService.getToken(pubno.getAppid(), pubno.getAppsecret());
			if (token == null) {
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, "获取TOKEN失败");
				return jsonObject;
			}
			JSONObject param = new JSONObject();
			param.put("content", content);
			param = WeixinUtil.httpRequest(WxConst.MSG_CHECK_URL + token, "POST", param);
			if (param.getIntValue(WxConst.ERR_CODE) != 0) {
				logger.info("内容检测：" + param.toString());
			}
			jsonObject.put(RESULT, param);
		}
		return jsonObject;
	}
	
	/**
	 * 图片鉴黄 图片大小限制：1M
	 * @param imgUrl
	 * @param appid
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/checkimg", method = RequestMethod.POST)
	public JSONObject checkImage(MultipartFile myimage, String appid) {
		JSONObject jsonObject = getJsonResult(myimage);
		if (jsonObject.getBoolean(SUCCESS)) {
			// 获取小程序信息
			WeixinPubno pubno = simpleCacheProvider.get(appid);
			if (pubno == null) {
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, "APP不存在");
				return jsonObject;
			}
			// 获取TOKEN
			String token = weixinService.getToken(pubno.getAppid(), pubno.getAppsecret());
			if (token == null) {
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, "获取TOKEN失败");
				return jsonObject;
			}
			// 图片检测
			try {
				jsonObject = WeChatApiUtil.checkImage(myimage.getInputStream(), token);
				jsonObject.put(SUCCESS, true);
				if (jsonObject.getIntValue(WxConst.ERR_CODE) != 0) {
					jsonObject.put(SUCCESS, false);
					jsonObject.put(MESSAGE, "图片有敏感内容");
					logger.info("图片检测：" + jsonObject);
				}
			} catch (IOException e) {
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, e.getMessage());
			}
		}
		return jsonObject;
	}
	
	@LoginValidate(value = false)
	@RequestMapping(value = "/checkimgQQ", method = RequestMethod.POST)
	public JSONObject checkImageQQ(MultipartFile myimage, String appid) {
		File tfile = null;
		JSONObject jsonObject = getJsonResult(myimage, appid);
		if (jsonObject.getBoolean(SUCCESS)) {
			// 获取小程序信息
			WeixinPubno pubno = simpleCacheProvider.get(appid);
			if (pubno == null) {
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, "APP不存在");
				return jsonObject;
			}
			// 获取TOKEN
			String token = weixinService.getToken(pubno.getAppid(), pubno.getAppsecret());
			if (token == null) {
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, "获取TOKEN失败");
				return jsonObject;
			}
			// 图片检测
			try {
				// MultipartFile -> File
				tfile = File.createTempFile("tmp", null);
				myimage.transferTo(tfile);
				// 封装请求参数
	            Part[] parts = new Part[] {
	            	new FilePart("media", tfile),
	            	new StringPart("access_token", token),
	            	new StringPart("appid", pubno.getAppid())
	            };
	            // 图片检测
	            jsonObject = WeChatApiUtil.uploadMedia(parts, WxConst.IMG_CHECK_URL_QQ);
	            jsonObject.put(SUCCESS, true);
				if (jsonObject.getIntValue("errCode") != 0) {
					jsonObject.put(SUCCESS, false);
					jsonObject.put(MESSAGE, "图片有敏感内容");
					logger.info("图片检测：" + jsonObject);
				}
			} catch (IOException e) {
				jsonObject.put(SUCCESS, false);
				jsonObject.put(MESSAGE, e.getMessage());
			} finally {
				if (tfile != null && tfile.exists()) {
					tfile.delete();
					tfile.deleteOnExit();
				}
			}
		}
		return jsonObject;
	}
	
	@Override
	protected String getBasePath() {
		return null;
	}
	
}
